package org.example.env_boot.service;


import org.example.env_boot.dto.ApiResponse;
import org.example.env_boot.entity.Admin;
import org.example.env_boot.entity.GridMember;
import org.example.env_boot.entity.Supervisor;
import org.example.env_boot.repository.AdminRepository;
import org.example.env_boot.repository.GridMemberRepository;
import org.example.env_boot.repository.SupervisorRepository;
import org.example.env_boot.util.JwtUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 认证服务类
 */
@Service
public class AuthService {
    
    private final AdminRepository adminRepository;
    private final GridMemberRepository gridMemberRepository;
    private final SupervisorRepository supervisorRepository;
    private final JwtUtil jwtUtil;
    
    public AuthService(AdminRepository adminRepository, GridMemberRepository gridMemberRepository, 
                      SupervisorRepository supervisorRepository, JwtUtil jwtUtil) {
        this.adminRepository = adminRepository;
        this.gridMemberRepository = gridMemberRepository;
        this.supervisorRepository = supervisorRepository;
        this.jwtUtil = jwtUtil;
    }
    
    /**
     * 管理员登录
     */
    public ApiResponse<Map<String, Object>> adminLogin(String adminCode, String password) {
        System.out.println("=== 管理员登录调试信息 ===");
        System.out.println("接收到的用户名: '" + adminCode + "'");
        System.out.println("接收到的密码: '" + password + "'");
        
        Optional<Admin> adminOpt = adminRepository.findByAdminCode(adminCode);
        
        if (adminOpt.isEmpty()) {
            System.out.println("管理员不存在: " + adminCode);
            return ApiResponse.error("管理员不存在");
        }
        
        Admin admin = adminOpt.get();
        System.out.println("数据库中的管理员信息:");
        System.out.println("  ID: " + admin.getAdminId());
        System.out.println("  Code: '" + admin.getAdminCode() + "'");
        System.out.println("  Password: '" + admin.getPassword() + "'");
        System.out.println("密码比较: '" + password + "' vs '" + admin.getPassword() + "'");
        System.out.println("密码相等: " + password.equals(admin.getPassword()));
        
        // 改为直接字符串比较，不使用加密验证
        if (!password.equals(admin.getPassword())) {
            System.out.println("密码比较失败!");
            return ApiResponse.error("密码错误");
        }
        
        System.out.println("登录成功!");
        String token = jwtUtil.generateToken(adminCode, "ADMIN", String.valueOf(admin.getAdminId()));
        
        // 构建userInfo Map，避免JSON序列化问题
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("adminId", admin.getAdminId());
        userInfo.put("adminCode", admin.getAdminCode());
        userInfo.put("remarks", admin.getRemarks());
        
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userInfo", userInfo);
        result.put("role", "ADMIN");
        
        System.out.println("返回的result数据: " + result);
        
        return ApiResponse.success("登录成功", result);
    }
    
    /**
     * 网格员登录
     */
    public ApiResponse<Map<String, Object>> gridMemberLogin(String gmCode, String password) {
        Optional<GridMember> gridMemberOpt = gridMemberRepository.findByGmCode(gmCode);
        
        if (gridMemberOpt.isEmpty()) {
            return ApiResponse.error("网格员不存在");
        }
        
        GridMember gridMember = gridMemberOpt.get();
        // 改为直接字符串比较，不使用加密验证
        if (!password.equals(gridMember.getPassword())) {
            return ApiResponse.error("密码错误");
        }
        
        String token = jwtUtil.generateToken(gmCode, "GRID_MEMBER", String.valueOf(gridMember.getGmId()));
        
        // 构建userInfo Map，避免JSON序列化问题
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("gmId", gridMember.getGmId());
        userInfo.put("gmCode", gridMember.getGmCode());
        userInfo.put("gmName", gridMember.getGmName());
        userInfo.put("gmPhone", gridMember.getGmPhone());
        userInfo.put("provinceId", gridMember.getProvinceId());
        userInfo.put("cityId", gridMember.getCityId());
        
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userInfo", userInfo);
        result.put("role", "GRID_MEMBER");
        
        return ApiResponse.success("登录成功", result);
    }
    
    /**
     * 公众监督员登录
     */
    public ApiResponse<Map<String, Object>> supervisorLogin(String supervisorCode, String password) {
        Optional<Supervisor> supervisorOpt = supervisorRepository.findBySupervisorCode(supervisorCode);
        
        if (supervisorOpt.isEmpty()) {
            return ApiResponse.error("公众监督员不存在");
        }
        
        Supervisor supervisor = supervisorOpt.get();
        // 改为直接字符串比较，不使用加密验证
        if (!password.equals(supervisor.getPassword())) {
            return ApiResponse.error("密码错误");
        }
        
        String token = jwtUtil.generateToken(supervisorCode, "SUPERVISOR", String.valueOf(supervisor.getSupervisorId()));
        
        // 构建userInfo Map，避免JSON序列化问题
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("supervisorId", supervisor.getSupervisorId());
        userInfo.put("supervisorCode", supervisor.getSupervisorCode());
        userInfo.put("supervisorName", supervisor.getSupervisorName());
        userInfo.put("supervisorPhone", supervisor.getSupervisorPhone());
        userInfo.put("provinceId", supervisor.getProvinceId());
        userInfo.put("cityId", supervisor.getCityId());
        
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userInfo", userInfo);
        result.put("role", "SUPERVISOR");
        
        return ApiResponse.success("登录成功", result);
    }
    
    /**
     * 公众监督员注册
     */
    public ApiResponse<Supervisor> supervisorRegister(String supervisorCode, String password, String supervisorName, String supervisorPhone, Integer provinceId, Integer cityId) {
        // 检查监督员编号是否已存在
        if (supervisorRepository.existsBySupervisorCode(supervisorCode)) {
            return ApiResponse.error("该监督员编号已被注册");
        }
        
        // 检查手机号是否已存在
        if (supervisorRepository.existsBySupervisorPhone(supervisorPhone)) {
            return ApiResponse.error("该手机号已被注册");
        }
        
        // 验证手机号格式
        if (!supervisorPhone.matches("^1[3-9]\\d{9}$")) {
            return ApiResponse.error("手机号格式不正确");
        }
        
        // 验证密码长度
        if (password.length() < 6 || password.length() > 20) {
            return ApiResponse.error("密码长度必须在6-20位之间");
        }
        
        // 创建新的公众监督员
        Supervisor supervisor = new Supervisor();
        supervisor.setSupervisorCode(supervisorCode);
        // 直接存储明文密码，不进行加密
        supervisor.setPassword(password);
        supervisor.setSupervisorName(supervisorName);
        supervisor.setSupervisorPhone(supervisorPhone);
        supervisor.setProvinceId(provinceId);
        supervisor.setCityId(cityId);
        
        Supervisor savedSupervisor = supervisorRepository.save(supervisor);
        
        return ApiResponse.success("注册成功", savedSupervisor);
    }
    
    /**
     * 根据Token获取用户信息
     */
    public ApiResponse<Map<String, Object>> getUserInfo(String token) {
        if (!jwtUtil.validateToken(token)) {
            return ApiResponse.unauthorized("Token无效");
        }
        
        String username = jwtUtil.getUsernameFromToken(token);
        String role = jwtUtil.getRoleFromToken(token);
        String userId = jwtUtil.getUserIdFromToken(token);
        
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", username);
        userInfo.put("role", role);
        userInfo.put("userId", userId);
        
        // 根据角色获取详细信息
        switch (role) {
            case "ADMIN":
                Optional<Admin> admin = adminRepository.findById(Integer.parseInt(userId));
                if (admin.isPresent()) {
                    userInfo.put("details", admin.get());
                }
                break;
            case "GRID_MEMBER":
                Optional<GridMember> gridMember = gridMemberRepository.findById(Integer.parseInt(userId));
                if (gridMember.isPresent()) {
                    userInfo.put("details", gridMember.get());
                }
                break;
            case "SUPERVISOR":
                Optional<Supervisor> supervisor = supervisorRepository.findById(Integer.parseInt(userId));
                if (supervisor.isPresent()) {
                    userInfo.put("details", supervisor.get());
                }
                break;
        }
        
        return ApiResponse.success("获取用户信息成功", userInfo);
    }
} 